import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '../store'
import 'url-search-params-polyfill'
import _ from 'lodash'

Vue.use(Router)
// history hash
const router = new Router({
    mode: 'hash',
    routes
})

let LOGIN_PAGE_NAME = 'login'
router.beforeEach((to, from, next) => {
    let token = localStorage.getItem('TOKEN_KEY')
    if (to.name === 'register') { // 跳转注册页面
        next() // 跳转
    } else if (!token && (to.name !== 'index' && to.name !== LOGIN_PAGE_NAME)) {
        next({ name: 'index' })
    } else if (!token && (to.name === 'index' || to.name == LOGIN_PAGE_NAME)) {
        if (!_.isEmpty(store.state.app.userInfo)) {
            next()
        } else {
            store.dispatch('geUntLoginMenus')
                .then(res => {
                    next()
                })
        }
    } else {
        if (!_.isEmpty(store.state.app.userInfo)) {
            next()
        } else {
            store.dispatch('getUserInfo')
                .then(res => {
                    next()
                })
                .catch(res => {
                    next(LOGIN_PAGE_NAME)
                })
        }
    }
});
//   if(to.name === 'register'){  // 跳转注册页面
//     next() // 跳转
//   }else if (!token && to.name !== LOGIN_PAGE_NAME ) {
//     // 未登录且要跳转的页面不是登录页
//     // next({name: LOGIN_PAGE_NAME})
//         // store.dispatch('geUntLoginMenus')
//         // next({name: 'index'})
//   } else if (!token && to.name === LOGIN_PAGE_NAME) {
//     // 未登陆且要跳转的页面是登录页
//     next() // 跳转
//   } else if (token && to.name === LOGIN_PAGE_NAME) {
//     next({   // 已登录且要跳转的页面是登录页
//       name: 'index' // 跳转到index页
//     })
//   } else {
//     if (!_.isEmpty(store.state.app.userInfo)) {
//       next()
//     } else {
//       store.dispatch('getUserInfo')
//         .then(res => {
//           next()
//         })
//         .catch(res => {
//           next(LOGIN_PAGE_NAME)
//         })
//     }
//   }
// });
export default router